# -*- coding: utf-8 -*-

#==============================================================================

from IPython import get_ipython
get_ipython().magic('reset -sf')

# import libraries

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
from scipy import misc


#==============================================================================

# Domain of simulated model
x_value_min = 0                   # Domain, min X 
x_value_max = 100                 # Domain, max X

y_line = 850                      # y of decoy line
p_return = 0.95                   # Probability that agent makes a choice
stream = 1000                    # Length of stream

# Sampling domain
sample_min = 0                    # Sample min
sample_max = 60                   # Sample max

#==============================================================================

# initialize some variables

track_x  = []                    # initialize x log
track_y =  []                    # initialize y log
track_x1 =  []

x = 0.0                          # set x to zero
t = 0.0                          # set t to zero
y = 0.0                          # set y to zero

#==============================================================================
#
# In the current simulation we make use of a Decoy decision model from:
#
# Trueblood, Jennifer S., Scott D. Brown, and Andrew Heathcote. 
# "The multiattribute linear ballistic accumulator model of context effects in 
# multialternative choice." 
# Psychological review 121.2 (2014): 179.
#
# The model of Trueblood et al is itself based on data from previous
# experiments. We will use it here to set the parameters of our simulation.
#
#==============================================================================


# import matrix graph from article

decoy_img = misc.imread("Decoy_Matrix.bmp")

plt.imshow(decoy_img)
plt.axhline(y=y_line,linewidth=1, color='g',linestyle='--')
plt.text(650-20, 650+20, "B", fontsize=12, color='w')
plt.text(decoy_img.shape[0]-650-20, 
         decoy_img.shape[0]-650-20, "A", fontsize=12, color='black')
         
plt.show()

# create brightness matrix 

decoy_img_brightness = decoy_img.sum(axis=2) / decoy_img.shape[2]

# set decoy accroding to brightness along the chosen line
# approximation, brightness seems not to be 1:1 to p, 
# but good enough for our purpose

decoy_y = decoy_img_brightness[y_line] / 255

# create xvalues, from x min to x max

decoy_x = np.arange(x_value_min, decoy_y.size)
decoy_x = (decoy_x / decoy_y.size) * x_value_max

# plot the decoy values as based on brightness data

plt.plot(decoy_x, decoy_y,linewidth=1,color="blue",linestyle='-')


# create a spline approximation of the decoy values 
# based on brightness data

spline = UnivariateSpline (decoy_x, decoy_y-0.04, k=4, s=1)
spline_roots = spline.derivative().roots()

# relevant local max - hardcoded, 
# might be neat to use second deriv pos check, ie
# spline.derivatives(spline.derivative().roots()[x])[1] == postive

spline_local_max = spline_roots[1]
plt.axvline(x=spline_local_max,linewidth=1, color='r')

# plot the spline in the same graph

plt.plot(decoy_x,spline(decoy_x), color="green",linewidth=1)

plt.show()

#==============================================================================
#
# We now get to the main loop of our simulation. 
#
# In this simulation, we will randomly sample decoy values 
# from within our sampling domain
# 
#==============================================================================

for i in range(0,stream):

    # set the time

    t = i
    
    ############# randomly sample between min and max ##################

    x = np.random.randint(sample_min, sample_max)
    
    # B = Target, A = Competitor - C moves along striped line.
    # Randomly pick A's or B's, according to decoy C.
    # Probability of A vs B is calculated from our Decoy decision model 
    # spline function.
    
    sampleChoice = np.random.choice(["B","A"], 
                                    size=(1,), 
                                    p=[spline(x), 1-spline(x)])  
        
    # did agent/subject choose A or B?
        
    if sampleChoice == 'B':
       yt = 1.0                                  # chooses B! Hurray!
    else:
       yt = 0.0                                  # did not choose B
       
    # agent does not always make choice   
       
    if np.random.binomial(1, p_return, 1)==1:    
       y = yt
       track_x  = np.append(track_x, x)                 # log x
       track_y = np.append(track_y, y)                  # log x0
       if (y==1.0):
           track_x1 = np.append(track_x1, x)


#==============================================================================

# binned histogram of where B has been choosen.
plt.hist(track_x1, normed=1, bins=20)
plt.show()

yy = np.bincount(track_x1.astype(int))
yy = yy.astype(float)
plt.plot(yy)
plt.xlim(sample_min, sample_max)
plt.show()


xx = np.arange(yy.size)
spl = UnivariateSpline (xx,yy)
spl.set_smoothing_factor(10000)
plt.plot(xx,spl(xx), color="green",linewidth=1)
plt.xlim(sample_min, sample_max)
plt.show()


#==============================================================================
